<template>
  <div style="padding: 30px">
    <div class="function-lan" style="width: 100%">
      <label for="userData" style="margin-right: 10px">用户名称:</label>
      <div class="search-for">
        <el-input
          class="search-for-ipt"
          clearable
          @clear="getUserData"
          prefix-icon="el-icon-search"
          v-model="search"
          placeholder="请输入用户名称进行搜索"
        ></el-input>
      </div>
      <!-- 搜索按钮 -->
      <div class="search-btn" @click="searchFor">
        <Buttons :text="text2"></Buttons>
      </div>
      <el-select
        v-model="value"
        filterable
        clearable
        :filter-method="pickData"
        placeholder="请选择小区"
        class="pick"
      >
        <el-option
          v-for="item in community_pick"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-date-picker
        v-model="pickerTime"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        align="right"
        @change="changeTime"
      >
      </el-date-picker>
      <!-- 筛选按钮 -->
      <div class="search-btn" @click="pickData">
        <Buttons :text="text3"></Buttons>
      </div>
    </div>
    <!-- table区域 -->
    <el-table
      :data="userData"
      style="margin-top: 40px"
      v-loading="listLoading"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column label="用户编号" prop="id"></el-table-column>
      <el-table-column label="用户昵称" prop="nickName"></el-table-column>
      <el-table-column label="性别" prop="sex">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex === '1'">男</el-tag>
          <el-tag v-if="scope.row.sex === '2'" type="danger">女</el-tag>
          <el-tag v-if="scope.row.sex === '0'" type="warning">未填写</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="社区" prop="community">
        <template slot-scope="scope">
          {{ scope.row.community | format }}
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormat"
        label="创建时间"
        width="180px"
        align="center"
        prop="create_time"
      >
      </el-table-column>
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="bottom-start"
          >
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="checkUserInfo(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <!-- 查看详情 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="查看详情"
            placement="bottom-start"
          >
            <router-link :to="'/nested/users/details/' + scope.row.id">
              <el-button
                type="primary"
                style="margin: 0 10px"
                icon="el-icon-s-promotion"
                size="mini"
              ></el-button>
            </router-link>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="删除管理员"
            placement="bottom"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="query.page_number"
      :limit.sync="query.page_size"
      @pagination="getUserData"
    />
    <el-dialog
      title="修改用户信息"
      :visible.sync="updateUserDialogVisible"
      width="50%"
      @close="updateUserDialogClosed"
    >
      <el-form
        :model="updateUserForm"
        :rules="updateUserFormRules"
        ref="updateUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户昵称" prop="username">
          <el-input v-model="updateUserForm.nickName" disabled></el-input>
        </el-form-item>
        <el-form-item label="id" prop="id">
          <el-input
            type="number"
            v-model.number="updateUserForm.id"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="角色 " prop="role_id">
          <el-select v-model="updateUserForm.role_id" placeholder="请选择">
            <el-option
              v-for="item in selectValue"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUserList,
  getTotal,
  removeUser,
  updateUserInfo,
  readUserInfo
} from "@/api/user-list";
import Buttons from "@/components/button/index.vue";
import Pagination from "@/components/Pagination";
import {
  updateUserFormRules,
  selectValues,
  pickerOptions
} from "@/config/user/index";
import { checkPermission } from "@/utils/hasPermission";
export default {
  name: "userInfo",
  components: {
    Buttons,
    Pagination
  },
  filters: {
    format: function(data) {
      if (data === "0") {
        return "未填写";
      }
      return data;
    }
  },
  watch: {
    pickerTime(val) {
      console.log(val);
    },
    value(val) {
      console.log(val);
      if (val === "") {
        delete this.query.community_name;
      }
    }
  },
  data() {
    return {
      query: {
        page_number: 1,
        page_size: 20
      },
      total: 0,
      text2: "搜索",
      text3: "筛选",
      search: "",
      listLoading: false,
      userData: [],
      checkDialogVisible: false,
      updateUserForm: [],
      updateUserDialogVisible: false,
      updateUserFormRules: {},
      selectValue: [],
      pickerOptions,
      pickerTime: [],
      community_pick: [],
      value: ""
    };
  },
  created() {
    this.updateUserFormRules = updateUserFormRules;
    this.selectValue = selectValues;
    this.pickerOptions = pickerOptions;
    this.getUserData();
  },
  methods: {
    checkPermission,
    async getUserData() {
      let self = this;
      self.listLoading = true;
      const res = await getUserList(self.query);
      self.userData = res.result.info;
      console.log(res);
      console.log(self.userData);
      const response = await getTotal();
      console.log(response);
      self.total = response.result[0].numbers;
      // 搜索筛选
      // let list = self.userData.filter(
      //   (item, index) =>
      //     item.name.includes(self.search) ||
      //     item.community.includes(self.search)
      // );
      // console.log(list);
      // self.userData = list;
      // self.userData = list.filter(
      //   (item, index) =>
      //     index < self.query.page_number * self.query.page_size &&
      //     index >= self.query.page_size * (self.query.page_number - 1)
      // );
      this.userData.map(item => {
        if (item.community == "0") {
          this.community_pick.push({ value: "未填写", label: "未填写" });
        } else {
          this.community_pick.push({
            value: item.community,
            label: item.community
          });
        }
      });
      const result = new Map();
      this.community_pick = this.community_pick.filter(arr => {
        return !result.has(arr.value) && result.set(arr.label, 1);
      });
      console.log(this.community_pick);
      setTimeout(() => {
        self.listLoading = false;
      }, 1.5 * 1000);
    },
    searchFor() {
      let self = this;
      this.listLoading = true;
      let reg = new RegExp(self.search.trim(), "i");
      let resArr = [];
      self.userData.filter(item => {
        for (let i in item) {
          // console.log(item[i]);
          if (reg.test(item[i])) {
            resArr.push(item);
          }
        }
      });
      // 去重
      const res = new Map();
      setTimeout(() => {
        this.userData = resArr.filter(arr => {
          return !res.has(arr.id) && res.set(arr.id, 1);
        });
        self.total = this.userData.length;
        self.listLoading = false;
      }, 1.5 * 500);
    },
    addUserDialog() {
      if (!this.checkPermission()) return;
    },
    async removeUserById(id) {
      if (!this.checkPermission()) return;
      let self = this;
      const confirmResult = await self
        .$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .catch(err => err);
      if (confirmResult !== "confirm") {
        return self.$message.info("已经取消删除");
      }
      const res = await removeUser(id);
      if (res.code !== 1) {
        return self.$message.error("删除失败！");
      }

      self.$message.success("删除成功！");
      self.getUserData();
    },
    async checkUserInfo(id) {
      if (!this.checkPermission()) return;
      let self = this;
      const res = await readUserInfo(id);
      self.updateUserForm = res.result[0];
      console.log(self.updateUserForm);
      self.updateUserDialogVisible = true;
    },
    // 时间格式化
    dateFormat(row, column) {
      // dateFormat();
      // console.log(row, column);
      var date = row[column.property];
      if (date == undefined) return "";
      return this.$moment.unix(date).format("YYYY-MM-DD HH:mm:ss");
    },
    updateUserDialogClosed() {
      this.$refs.updateUserFormRef.resetFields();
    },
    updateUser() {
      let self = this;
      self.$refs.updateUserFormRef.validate(async valid => {
        if (!valid) return;
        const res = await updateUserInfo({
          id: self.updateUserForm.id,
          role_id: self.updateUserForm.role_id
        });
        if (res.code !== 1) {
          return self.$message.error("修改用户信息失败！");
        }
        self.$message.success("修改用户信息成功！");
      });
      self.getUserData();
      self.updateUserDialogVisible = false;
    },
    async pickData() {
      let self = this;
      // this.query.start_time = new Date(this.pickerTime[0]).getTime();
      // this.query.end_time = new Date(this.pickerTime[1]).getTime();
      if (this.pickerTime !== null) {
        this.query.start_time = this.pickerTime[0];
        this.query.end_time = this.pickerTime[1];
      }
      // console.log(this.query.start_time, this.query.end_time);
      if (this.value) {
        this.query.community_name = this.value == "未填写" ? "0" : this.value;
      }
      this.listLoading = true;
      const res = await getUserList(self.query);
      console.log(res.result);
      setTimeout(() => {
        this.userData = res.result.info;
        this.total = res.result.count[0].count_number;
        self.listLoading = false;
      }, 1.5 * 500);
    },
    changeTime(val) {
      console.log(val);
      if (val === null) {
        delete this.query.start_time;
        delete this.query.end_time;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.search-btn {
  margin-left: 10px;
  margin-right: auto;
}
.function-lan {
  align-items: center;
}
.pick {
  margin-right: 20px;
}
</style>
